package business.global.pk.nn;

import business.global.room.base.AbsRoomPos;
import business.nn.c2s.cclass.NNRoomSetInfo;
import business.nn.c2s.cclass.NN_define.NN_GameStatus;
import business.nn.c2s.iclass.*;
import cenum.RoomTypeEnum;
import cenum.room.DissolveNoticeTypeEnum;
import com.ddm.server.common.utils.CollectionUtils;
import com.ddm.server.common.utils.CommTime;
import com.ddm.server.websocket.handler.requset.WebSocketRequest;
import jsproto.c2s.cclass.pk.Victory;
import jsproto.c2s.iclass.room.SBase_Dissolve;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;


/**
 * 牛牛一局游戏逻辑
 * 主动下锅是在第三轮游戏结束之后的界面还是，第四轮开始界面
 * @author zaf
 *
 */

public class NNRoomSet_DGN extends NNRoomSet{

	public NNRoomSet_DGN(NNRoom room,int guodi,NNRoomSet_DGN lastSet, Map<Integer,Integer> winControlMap) {
		super(room,guodi,lastSet,winControlMap);
	}

	/**
	 * 每200ms更新1次   秒
	 * @param sec 
	 * @return T 是 F 否
	 */
	public boolean update(int sec) {
		boolean isClose = false;
		switch(this.getStatus()){
			case NN_GAME_STATUS_SELECT_BACKER:
				if( CommTime.nowMS() - this.startMS >=  this.getWaitTimeByStatus()){

					this.startMS = CommTime.nowMS();
					if(zhuangStatus==3){//xiazhuang
						startSendCard(1);
					}else if(zhuangStatus==2){//xuzhuang
							newguo(currentPos,true);
					}else{
						selectNum++;
						currentPosIndex++;
						currentPosIndex = currentPosIndex%availablePosList.size();
						currentPos = availablePosList.get(currentPosIndex);
						/*if(selectNum>=availablePosList.size()){
							this.guodiCur = guodi*multi;
							guoNum=1;
							room.addDaoNum(1);
							startSendCard(1);


						}else{
							zhuangStatus = 1;
							this.getRoomPlayBack().playBack2All(SNN_Xuanzhuang.make(currentPos));
						}*/
						newguo(currentPos,true);
					}
				}
				break;
			case NN_GAME_STATUS_SENDCARD_ONE:
				if( CommTime.nowMS() - this.startMS >=  this.getWaitTimeByStatus()){
					this.onSendCardOneEnd();
				}
				break;
			case NN_GAME_STATUS_BET:
				if( CommTime.nowMS() - this.startMS >=  this.getWaitTimeByStatus()){
					this.onBetEnd();
				}
				break;
			case NN_GAME_STATUS_SENDCARD_SECOND:
				if( CommTime.nowMS() - this.startMS >=  this.getWaitTimeByStatus()){
					this.onSendCardEnd();
				}
				break;
			case NN_GAME_STATUS_RESULT:
				if( CommTime.nowMS() - this.startMS >=  this.getWaitTimeByStatus()){

				}
				break;
			case NN_GAME_STATUS_END:
				isClose = true;
				break;
			default:
				break;
		}
		return isClose;
	}

	private void startSendCard(int multi) {
		this.multi = multi;
		this.setBackerPos(currentPos, false);
		this.setStatus(NN_GameStatus.NN_GAME_STATUS_SENDCARD_ONE);

		this.sendTuZhuPoint();
	}


	//第一次发牌结束
	public void onSendCardOneEnd() {
		this.setStatus(NN_GameStatus.NN_GAME_STATUS_BET);
		this.getRoomPlayBack().playBack2All(SNN_StatusChange.make(this.room.getRoomID(), this.getStatus().value(), this.startMS, this.getSendCardNumber(),  this.getBackerPos(), this.isRandBackPos(), new ArrayList<>(), this.callbackerList, guodiCur,room.getDaoNum()));
	}
	
	//抢庄结束
	@Override
	public void onHogEnd(){		
		int rand = 0;
		
		boolean isRandBackerPos = true;
		if (this.getCallBackerCount() > 0) {
			if (this.getCallBackerCount() <= 1) {
				isRandBackerPos = false;
			}
			rand = (int) (Math.random()*this.callbackerList.size());

			Victory vic = this.callbackerList.get(rand);
			if(null != vic && vic.getNum() == 1){
				rand =vic.getPos();
			} else {
				for(int i = 0 ;i < this.callbackerList.size(); i++){
					rand = (rand + 1) % this.callbackerList.size();
					Victory temp = this.callbackerList.get(rand);
					if(null != temp && temp.getNum() == 1){
						rand =temp.getPos();
						break;
					}
				}
			}
		
		}else{
			rand = this.getRandPos();
		}
		int callbacker = rand;
		
		
		this.setBackerPos(callbacker, isRandBackerPos);
		
		this.setStatus(NN_GameStatus.NN_GAME_STATUS_ONSURECALLBACKER);

		this.sendTuZhuPoint();
	}
	

	@Override
	public int getSendCardNumber() {
		// TODO 自动生成的方法存根
		int count = 4;
		if(this.getStatus() == NN_GameStatus.NN_GAME_STATUS_SENDCARD_SECOND)
		{
			count = 1;
		}
		return count;
	}

	@Override
	public NN_GameStatus getStartStatus() {
		this.startMS = CommTime.nowMS();
		// TODO 自动生成的方法存根
		if(round>=3&&guodiCur>0){
			zhuangStatus = 3;
			this.getRoomPlayBack().playBack2All(SNN_Xiazhuang.make(currentPos, this.startMS));
			return NN_GameStatus.NN_GAME_STATUS_SELECT_BACKER;

		}else if(guodiCur==0 && guoNum == 1 && round < 4){
			room.startNewGuo = true;
			NNRoomPos setpos = (NNRoomPos) this.room.getRoomPosMgr().getPosByPosID(currentPos);
			if(round>=1&&setpos!=null&&(setpos.getRoomSportsPoint()>=guodi*multi*2|| !RoomTypeEnum.UNION.equals(this.room.getRoomTypeEnum()))){
				zhuangStatus = 2;
				this.getRoomPlayBack().playBack2All(SNN_Xuzhuang.make(currentPos, this.startMS));
				return NN_GameStatus.NN_GAME_STATUS_SELECT_BACKER;
			}
		}
		if(room.startNewGuo || guodiCur<=0){
			newguo(currentPos,false);
			return NN_GameStatus.NN_GAME_STATUS_SELECT_BACKER;
		}else{
			this.setBackerPos(currentPos, false);
			return NN_GameStatus.NN_GAME_STATUS_SENDCARD_ONE;
		}
	}

	private void newguo(int curPos,boolean xuan) {
		round = 0;
		room.startNewGuo = false;
		availablePosList = new ArrayList<>();
		//这里初始化所有有资格当庄的玩家,如果是首局随机一个初始玩家，如果不是首局，从上个庄家开始找对应的下一个庄
		if(RoomTypeEnum.UNION.equals(this.room.getRoomTypeEnum())){

			for (int i = 0; i < this.room.getPlayerNum(); i++) {
				AbsRoomPos roomPos = this.room.getRoomPosMgr().getPosByPosID(i);
				if(null == roomPos) {
					continue;
				}
				if(roomPos.getPid()==0) {
					continue;
				}
//				if(roomPos.getRoomSportsPoint()>=guodi|| !RoomTypeEnum.UNION.equals(this.room.getRoomTypeEnum())) {
				if(roomPos.getRoomSportsPoint() >= this.room.roomCfg.sztj || !RoomTypeEnum.UNION.equals(this.room.getRoomTypeEnum())) {
					availablePosList.add(i);
				}
			}
		}else{

			for (int i = 0; i < this.room.getPlayerNum(); i++) {
				AbsRoomPos roomPos = this.room.getRoomPosMgr().getPosByPosID(i);
				if(null == roomPos) {
					continue;
				}
				if(roomPos.getPid()==0) {
					continue;
				}
				availablePosList.add(i);
			}
		}
		if(curPos<0){
			currentPosIndex = random.nextInt(availablePosList.size());
		}else{
			for (int i = 0; i < availablePosList.size(); i++) {
				if(availablePosList.get(i)==curPos){
					currentPosIndex=(i+1) % availablePosList.size();
					break;
				}
			}
		}
		currentPos = availablePosList.get(currentPosIndex);
		selectNum = 0;
		zhuangStatus = 1;

		//这里记录询问次数 如果询问次数超过可当庄人数，则结束当局
		this.xuanZhuangNum++;
		if(this.room.getDaoNum() == this.room.getBaseRoomConfigure().getBaseCreateRoom().getPlayerNum() || this.xuanZhuangNum > availablePosList.size() || CollectionUtils.isEmpty(availablePosList)){
			if(this.getSetID() == 1){
				this.room.getRoomPosMgr().notify2All(this.room.Dissolve(SBase_Dissolve.make(this.room.getRoomID(), DissolveNoticeTypeEnum.CHANGE_ROOMCRG.ordinal(), false)));
			}
			this.room.endRoom();
			return;
		}
		this.startMS = CommTime.nowMS();
		this.getRoomPlayBack().playBack2All(SNN_Xuanzhuang.make(currentPos, this.startMS));
	}

	@Override
	public void resultCalc() {
		// TODO 自动生成的方法存根
		NNGameResult result = new NNGameResult(this.room);
		guodiCur = result.calcByCallBacker(guodiCur);
	}



	@Override
	public void setDefeault() {
		// TODO 自动生成的方法存根

	}


	@Override
	public NNRoomSetInfo getNotify_set(long pid) {
		NNRoomSetInfo result = super.getNotify_set(pid);
		if(this.status==NN_GameStatus.NN_GAME_STATUS_SELECT_BACKER){
			result.zhuangStatus = zhuangStatus;
			result.zhuangPos = currentPos;
		}
		return result;
	}

	public void onXuanzhuang(WebSocketRequest request, CNN_Xuanzhuang req) {
		if(req.xuan==0){
			newguo(currentPos,false);
		}else{
			guoNum=1;
			//第一局的时候不加1 panvc
			if(getSetID() != 1){
				room.addDaoNum(1);
			}
			this.guodiCur = guodi*multi;
			startSendCard(1);
		}
	}

	public void onXuzhuang(WebSocketRequest request, CNN_Xuzhuang req) {
		//如果当前锅底数为0，续庄的话，锅底翻倍，锅数加1，
		if(req.xu==0){
			newguo(currentPos,true);
		}else{
			guoNum++;
			round = 0;
			room.startNewGuo = false;
			if(guodiCur==0){
				this.guodiCur = guodi*multi*2;
				startSendCard(multi*2);
			}else {

			}
		}
	}

	@Override
	public void onXiazhuang(WebSocketRequest request, CNN_Xiazhuang req) {
		if(req.xia==1){
			newguo(currentPos,true);
		}else{
			startSendCard(1);
		}
	}
}
